<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
    <div
      class="max-w-md w-full space-y-8 bg-white p-8 rounded-lg shadow-md transition-all duration-300 hover:shadow-lg">
      <!-- 标题区域 -->
      <div class="flex flex-col items-center justify-center">
        <h1 class="text-2xl font-bold text-gray-900 text-center">找回密码</h1>
        <p class="mt-2 text-sm text-gray-500 text-center">
          请输入您的邮箱，我们将发送验证码到该邮箱
        </p>
      </div>

      <!-- 步骤指示器 -->
      <div class="flex items-center justify-between mb-8">
        <div class="flex flex-col items-center">
          <div class="w-8 h-8 rounded-full flex items-center justify-center bg-primary text-white text-sm"
            :class="{ 'bg-blue-500 text-gray-0': step === 1, 'bg-gray-200 text-gray-500': step !== 1 }">
            1
          </div>
          <span class="mt-1 text-xs text-gray-500">验证邮箱</span>
        </div>
        <div class="flex-1 h-0.5 mx-2 bg-gray-200">
          <div class="h-full bg-primary transition-all duration-500" :style="{ width: step >= 2 ? '100%' : '0%' }">
          </div>
        </div>
        <div class="flex flex-col items-center">
          <div class="w-8 h-8 rounded-full flex items-center justify-center bg-primary text-white text-sm"
            :class="{ 'bg-blue-500 text-gray-0': step === 2, 'bg-gray-200 text-gray-500': step !== 2 }">
            2
          </div>
          <span class="mt-1 text-xs text-gray-500">验证 code</span>
        </div>
        <div class="flex-1 h-0.5 mx-2 bg-gray-200">
          <div class="h-full bg-primary transition-all duration-500" :style="{ width: step >= 3 ? '100%' : '0%' }">
          </div>
        </div>
        <div class="flex flex-col items-center">
          <div class="w-8 h-8 rounded-full flex items-center justify-center bg-primary text-white text-sm"
            :class="{ 'bg-blue-500 text-gray-0': step === 3, 'bg-gray-200 text-gray-500': step !== 3 }">
            3
          </div>
          <span class="mt-1 text-xs text-gray-500">设置密码</span>
        </div>
      </div>

      <!-- 表单内容 -->
      <el-form ref="forgotForm" :model="formData" :rules="stepRules" class="mt-4 space-y-6"
        @submit.prevent="handleSubmit">
        <!-- 第一步：输入邮箱 -->
        <template v-if="step === 1">
          <el-form-item prop="email">
            <el-input v-model="formData.email" placeholder="请输入您的邮箱" type="email" prefix-icon="Message"
              autocomplete="email" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" native-type="submit" class="w-full" :loading="loading">
              发送验证码
            </el-button>
          </el-form-item>
        </template>

        <!-- 第二步：输入验证码 -->
        <template v-if="step === 2">
          <el-form-item prop="code">
            <el-input v-model="formData.code" placeholder="请输入邮箱收到的验证码" type="text" prefix-icon="Key"
              autocomplete="one-time-code">
              <template #append>
                <el-button type="text" @click="sendCode" :disabled="countingDown || loading" class="text-primary">
                  {{ countingDown ? `${countDownSeconds}s 后重新发送` : '重新发送' }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <div class="flex space-x-2">
            <el-button type="default" @click="step = 1" class="flex-1" :loading="loading">
              上一步
            </el-button>
            <el-button type="primary" native-type="submit" class="flex-1" :loading="loading">
              验证验证码
            </el-button>
          </div>
        </template>

        <!-- 第三步：设置新密码 -->
        <template v-if="step === 3">
          <el-form-item prop="password">
            <el-input v-model="formData.password" placeholder="请输入新密码" type="password" prefix-icon="Lock" show-password
              autocomplete="new-password" />
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input v-model="formData.confirmPassword" placeholder="请确认新密码" type="password" prefix-icon="Lock"
              show-password autocomplete="new-password" />
          </el-form-item>

          <div class="flex space-x-2">
            <el-button type="default" @click="step = 2" class="flex-1" :loading="loading">
              上一步
            </el-button>
            <el-button type="primary" native-type="submit" class="flex-1" :loading="loading">
              重置密码
            </el-button>
          </div>
        </template>
      </el-form>

      <!-- 返回登录链接 -->
      <div class="text-center mt-6 text-sm text-gray-600">
        想起密码了？
        <router-link to="/login" class="text-primary text-blue-700 hover:text-primary/80 transition-colors">返回登录</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'

// 导入工具函数和API
import { genCode } from './util/index.js'
import { sendEmail, toReg, checkEmail, resetPass } from './api/index.js'
const router = useRouter()

// 当前步骤：1-验证邮箱，2-验证验证码，3-设置密码
const step = ref(1)
// 加载状态
const loading = ref(false)
// 倒计时相关
const countingDown = ref(false)
const countDownSeconds = ref(60)
let countDownTimer = null

// 表单数据
const formData = reactive({
  email: '',
  code: '',
  password: '',
  confirmPassword: ''
})

// 表单验证规则（根据不同步骤动态切换）
const stepRules = computed(() => {
  if (step.value === 1) {
    return {
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ]
    }
  } else if (step.value === 2) {
    return {
      code: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
      ]
    }
  } else {
    return {
      password: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== formData.password) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }
  }
})

// 发送验证码
const sendCode = async () => {
  if (!formData.email) {
    ElMessage.warning('请先输入邮箱')
    return
  }

  // 简单验证邮箱格式
  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailReg.test(formData.email)) {
    ElMessage.warning('请输入正确的邮箱格式')
    return
  }

  try {
    loading.value = true
    // 调用发送验证码接口
    const params = {
      email: formData.email.trim(),
      code: genCode(),
      type: 'repass'
    }
    const res = await sendEmail(params)
    if (res?.code === 200) {
      ElMessage.success('验证码已发送至您的邮箱，请查收')
    } else {
      ElMessage.error(res?.message || '发送验证码失败，请稍后重试')
    }
    // 开始倒计时
    startCountDown()
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error(error.message || '发送验证码失败，请稍后重试')
  } finally {
    loading.value = false
  }
}


//校验验证码
const checkCode = async () => {
  try {
    const res = await checkEmail({ code: formData.code })
    if (res.code === 200) {
      ElMessage.success('验证码验证成功')
      step.value = 3
    } else {
      ElMessage.error(res?.message || '验证码验证失败，请稍后重试')
    }
  } catch (error) {
    console.error('验证码验证失败:', error)
    ElMessage.error(error.message || '验证码验证失败，请稍后重试')
  }
}


//重置密码
const resetPassword = async () => {
  try {
    let params = {
      email: formData.email,
      password: formData.password,
      code: formData.code,
    }
    const res = await resetPass(params)
    if (res.code === 200) {
      ElMessage.success('密码重置成功')
      router.push('/login')
    } else {
      ElMessage.error(res?.message || '密码重置失败，请稍后重试')
    }
  } catch (error) {
    console.error('充值密码失败:', error)
    ElMessage.error(error.message || '充值密码失败，请稍后重试')
  }
}
// 开始倒计时
const startCountDown = () => {
  countingDown.value = true
  countDownSeconds.value = 60

  if (countDownTimer) {
    clearInterval(countDownTimer)
  }

  countDownTimer = setInterval(() => {
    countDownSeconds.value--
    if (countDownSeconds.value <= 0) {
      clearInterval(countDownTimer)
      countingDown.value = false
      countDownTimer = null
    }
  }, 1000)
}

// 清理定时器
const cleanup = () => {
  if (countDownTimer) {
    clearInterval(countDownTimer)
    countDownTimer = null
  }
}

// 组件卸载时清理定时器
onUnmounted(cleanup)

// 提交表单处理
const handleSubmit = async () => {
  try {
    loading.value = true
    if (step.value === 1) {
      // 第一步：验证邮箱并发送验证码
      await sendCode()
      step.value = 2
    } else if (step.value === 2) {
      // 第二步：验证验证码
      checkCode()
      step.value = 3
    } else {
      // 第三步：重置密码
      resetPassword()
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>